﻿using BootstrapBlazor.Components;
using Microsoft.AspNetCore.Components;
using LaserMark.DataAccess;
using LaserMark.DataAccess.Models;
using LaserMark.DataAccess.Service;
using System.Linq;

namespace LaserMark.Components;

public partial class Machine
{
    [Inject]
    [NotNull]
    private IMachineService? MachineService { get; set; }

    [Inject]
    [NotNull]
    private ISecretService? SecretService { get; set; }

    [NotNull]
    private List<MachineSetting>? Value { get; set; } = new();

    private Task<QueryData<MachineSetting>> OnQueryAsync(QueryPageOptions option)
    {
        using (var db = DbManager.Create())
        {
            var items = db.Query<MachineSetting>().Where(s => s.Key != "AxisCode");
            return Task.FromResult(new QueryData<MachineSetting>() { Items = items.ToList() });
        }
    }

    private Task<bool> OnSaveAsync(MachineSetting machine, ItemChangedType itemChangedType)
    {
        Value.Add(machine);
        return Task.FromResult(true);
    }

    private async Task<bool> OnSave(string password)
    {
        if (Value != null)
        {
            var ret = await SecretService.GetSecret("Factory", password);
            if (ret)
            {
                return await MachineService.UpdateMachine(Value);
            }
            else
            {
                return false;
            }
        }
        else
        {
            return false;
        }
    }

    private Task OnValueChanged(MachineSetting machine, double v)
    {
        Value.Add(machine);
        return Task.CompletedTask;
    }
}
